// 图片处理模块

// 标记是否正在进行裁剪
let isCropping = false;
let cropper = null; // 图片裁剪器实例
let croppedImage = null; // 裁剪后的图片

// 打开图片裁剪模态框
export function openCropModal(file) {
    if (!file) {
        console.error('没有文件可裁剪');
        return;
    }
    
    // 防止重复调用
    if (isCropping) {
        return;
    }
    
    // 设置裁剪中状态
    isCropping = true;
    
    const cropModal = document.getElementById('crop-modal');
    const cropperImage = document.getElementById('cropper-image');
    
    if (!cropModal || !cropperImage) {
        console.error('找不到裁剪模态框或图片元素');
        isCropping = false;
        return;
    }
    
    // 销毁之前的裁剪器
    if (cropper) {
        try {
            cropper.destroy();
        } catch (error) {
            console.error('销毁旧裁剪器失败:', error);
        }
        cropper = null;
    }
    
    // 显示模态框
    cropModal.classList.remove('hidden');
    
    // 创建图片URL
    const reader = new FileReader();
    reader.onerror = function(error) {
        console.error('读取文件失败:', error);
        isCropping = false;
    };
    
    reader.onload = function(e) {
        cropperImage.src = e.target.result;
        
        // 初始化裁剪器 - 添加延时确保图片已加载
        setTimeout(() => {
            try {
                cropper = new Cropper(cropperImage, {
                    aspectRatio: 1,
                    viewMode: 1,
                    dragMode: 'move',
                    autoCropArea: 0.8,
                    preview: '.preview',
                    guides: true,
                    center: true,
                    highlight: false,
                    cropBoxMovable: true,
                    cropBoxResizable: true,
                    toggleDragModeOnDblclick: false,
                    ready: function() {}
                });

            } catch (error) {
                console.error('初始化裁剪器失败:', error);
                isCropping = false;
            }
        }, 200);
    };
    
    try {
        reader.readAsDataURL(file);
    } catch (error) {
        console.error('读取文件失败:', error);
        isCropping = false;
    }
    
    // 重置文件输入框，防止选择相同文件时不触发change事件
    const uploadInput = document.getElementById('upload-image');
    if (uploadInput) uploadInput.value = '';
}

// 确认裁剪
export function confirmCrop() {
    if (!cropper) {
        console.error('裁剪器不存在，无法完成裁剪');
        isCropping = false;
        return;
    }
    
    try {
        // 获取裁剪后的图片数据
        const canvas = cropper.getCroppedCanvas({
            width: 200,
            height: 200,
            fillColor: 'transparent',
            imageSmoothingEnabled: true,
            imageSmoothingQuality: 'high'
        });
        
        if (!canvas) {
            console.error('无法创建裁剪画布');
            isCropping = false;
            return;
        }
        
        // 转换为base64 - 使用PNG格式保留透明度
        croppedImage = canvas.toDataURL('image/png');

        
        // 更新预览
        document.getElementById('preview-img').src = croppedImage;
        document.getElementById('image-preview').classList.remove('hidden');
        
        // 设置裁剪图片值
        document.getElementById('custom-image').value = croppedImage;
        
        // 关闭裁剪模态框
        closeCropModal();
    } catch (error) {
        console.error('裁剪过程出错:', error);
        alert('图片裁剪失败，请重试');
        isCropping = false;
    }
}

// 关闭裁剪模态框
export function closeCropModal() {
    const cropModal = document.getElementById('crop-modal');
    if (!cropModal) {
        isCropping = false;
        return;
    }
    
    try {
        // 销毁裁剪器
        if (cropper) {
            cropper.destroy();
            cropper = null;
        }
        
        // 隐藏模态框
        cropModal.classList.add('hidden');

    } catch (error) {
        console.error('关闭裁剪模态框出错:', error);
        // 强制隐藏模态框
        cropModal.style.display = 'none';
    } finally {
        // 无论如何，重置裁剪状态
        isCropping = false;
    }
}

// 设置图片上传相关事件
export function setupImageUploadEvents() {
    
    // 清除所有之前的事件监听器
    const elementsToClone = ['upload-button', 'upload-image', 'change-image', 'crop-close', 'crop-confirm'];
    
    elementsToClone.forEach(id => {
        const element = document.getElementById(id);
        if (element) {
            // 克隆并替换元素以移除所有事件监听器
            const newElement = element.cloneNode(true);
            if (element.parentNode) {
                element.parentNode.replaceChild(newElement, element);
            }
        }
    });
    
    // 重新获取新的干净元素
    const uploadButton = document.getElementById('upload-button');
    const uploadInput = document.getElementById('upload-image');
    const changeImageBtn = document.getElementById('change-image');
    const cropCloseBtn = document.getElementById('crop-close');
    const cropConfirmBtn = document.getElementById('crop-confirm');
    
    // 图标类型切换
    const iconTypeRadios = document.querySelectorAll('input[name="icon-type"]');
    
    iconTypeRadios.forEach(radio => {
        radio.addEventListener('change', () => {
            const type = radio.value;
            if (typeof window.showIconOptions !== 'undefined') {
                window.showIconOptions(type);
            }
            
            if (type === 'image' && typeof window.toggleImageUpload !== 'undefined') {
                window.toggleImageUpload(true);
            }
        });
    });
    
    // 上传图片按钮
    if (uploadButton && uploadInput) {
        uploadButton.onclick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            uploadInput.click();
        };
        
        uploadInput.onchange = function(e) {
            if (e.target.files && e.target.files[0]) {
                const file = e.target.files[0];
                openCropModal(file);
                e.stopPropagation();
                e.preventDefault();
                return false;
            }
        };
    }
    
    // 更换图片按钮
    if (changeImageBtn && uploadInput) {
        changeImageBtn.onclick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            uploadInput.click();
        };
    }
    
    // 裁剪模态框按钮
    if (cropCloseBtn) {
        cropCloseBtn.onclick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            closeCropModal();
        };
    }
    
    if (cropConfirmBtn) {
        cropConfirmBtn.onclick = function(e) {
            e.preventDefault();
            e.stopPropagation();
            confirmCrop();
        };
    }
}

// 导出模块
export default {
    openCropModal,
    confirmCrop,
    closeCropModal,
    setupImageUploadEvents,
    getCroppedImage: () => croppedImage
};